package cn.huanghuai.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 代理开发模式拦截请求，如果报异常，则都在这里处理
 */
//拦截所有加@RestController、@Controller类中的请求
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//返回json数据给前端
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    //处理异常类型
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if (ex.getMessage().contains("Duplicate entry")){
            return R.error("用户名重复，请换一个^-^");
        }
        return R.error("未知错误|v|");
    }

    //处理异常类型
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
